package com.ef.web.action;

import java.io.PrintWriter;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.hibernate.Criteria;
import org.hibernate.criterion.MatchMode;

import com.ef.constant.ConfirmMessage;
import com.ef.domain.Company;
import com.ef.service.CompanyService;
import com.ef.util.CustomExample;

public class CompanyAction extends BaseAction<Company> {

	private static final long serialVersionUID = 1L;

	protected CompanyService companyService;

	protected final org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory
			.getLog(CompanyAction.class);

	@SuppressWarnings("serial")
	public String list() {
		this.listResult = companyService.findByExample(
				new CustomExample<Company>(this.getModel()) {
					public void appendCondition(Criteria criteria) {
						this.enableLike(MatchMode.ANYWHERE);
					}
				}, this.getStartIndex(), this.getPageSize());
		return LIST;
	}

	public String edit() {

		return EDIT;
	}

	public String save() {
		saveCompany();
		this.setResult(ConfirmMessage.COMPANY);
		return EDIT;
	}

	protected Company saveCompany() {
		Company company = this.getModel();
		company.setUpdateTime(new Date());
		company.setUpdateUser(getSessionUser());
		companyService.saveOrUpdate(company);
		return company;
	}

	public String delete() {
		String ids = getRequest().getParameter("ids");
		String[] id = ids.split(",");
		for (String i : id) {
			companyService.delete(companyService.findById(Long.valueOf(i)));
		}

		return DELETE;
	}

	// 
	public String autoCompleteAjax() {
		HttpServletResponse response = ServletActionContext.getResponse();
		HttpServletRequest request = ServletActionContext.getRequest();
		response.setHeader("Cache-Control", "no-cache");
		response.setContentType("text/plain;charset=GBK ");
		PrintWriter out = null;
		try {
			String q = request.getParameter("q");
			String limit = request.getParameter("limit");
			List<Company> list = companyService.findByAnything(q, Integer
					.valueOf(limit));
			// {id:id,name:name}
			String responseStr = "";
			// System.out.println(q);
			out = response.getWriter();
			for (Company key : list) {
				responseStr = ("{id:") + (key.getId()) + (",name:\"")
						+ (key.getName()) + ("\"}");
				// System.out.println(responseStr);
				out.println(responseStr);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (Exception e) {

				}
			}
		}
		return null;
	}

	public CompanyService getCompanyService() {
		return companyService;
	}

	public void setCompanyService(CompanyService companyService) {
		this.companyService = companyService;
	}

}
